package com.zdsoft.wms.controller;

import com.zdsoft.wms.auth.CheckAuthorization;
import com.zdsoft.wms.auth.CheckLogin;
import com.zdsoft.wms.bean.User;
import com.zdsoft.wms.common.ServerResponse;
import com.zdsoft.wms.service.UserService;
import com.zdsoft.wms.utils.CookieUtil;
import com.zdsoft.wms.utils.JwtOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Value("${server.port}")
    private  String port;
    @Autowired
    UserService userService;

    @Autowired
    JwtOperator jwtOperator;
    @PostMapping("/login")
    public ServerResponse login(String name, String password, HttpServletResponse response){
        User user=userService.findByNameAndPassword(name,password);
        if (user!=null){
            Map<String,Object> userInfo=new HashMap<>(3);
            userInfo.put("id",user.getId());
            userInfo.put("name",user.getName());
            userInfo.put("role", user.getRole());
            user.setPassword("");
            String token=this.jwtOperator.generateToken(userInfo);
            CookieUtil.writeLoginToken(response,token);
            return ServerResponse.createBySuccess("登录成功",user);
        }
        return ServerResponse.createByErrorMessage("没有该用户");
    }
    @CheckAuthorization("TEACHER")
    @GetMapping("/serinfo/{serstation}")
    public ServerResponse  findAllBySerstationId(@PathVariable("serstation") int serstationId){
            List<User> users=userService.findAllBySerstationId(serstationId);
            return  ServerResponse.createBySuccess(serstationId+"所有用户",users);
    }

    @CheckLogin
    @GetMapping("/info/{id}")
    public ServerResponse  findInfoById(@PathVariable("id") int id){
       User user=userService.findById(id);
        return  ServerResponse.createBySuccess("用户信息"+port,user);
    }
}
